package com.android.functionmanagement.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.android.functionmanagement.ControlCenter;
import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.service.AlertService;
import com.android.functionmanagement.service.DaemonService;
import com.android.functionmanagement.service.PedometerService;
import com.android.functionmanagement.util.DeviceUtils;
import com.android.functionmanagement.util.LoadUserInfo;
import com.android.functionmanagement.util.SharedPreferencesUtils;
import com.android.functionmanagement.util.UploadData;

import org.json.JSONObject;

import java.util.HashMap;

public class BootCompletedReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
			boolean isGatherData = (Boolean) SharedPreferencesUtils.getParam(
					context, ConstantGloble.GATHER_DATA_SWITCH,
					ConstantGloble.DEFAULT_GATHER_DATA_STATUS);
			int gatherPeriod = Integer
					.parseInt(ConstantGloble.DEFAULT_GATHER_DATA_PERIOD);
			try {
				gatherPeriod = Integer.parseInt(SharedPreferencesUtils
						.getParam(context, ConstantGloble.GATHER_DATA_PERIOD,
								ConstantGloble.DEFAULT_GATHER_DATA_PERIOD)
						.toString()) * 60 * 1000;
			} catch (NumberFormatException e) {
				// TODO: handle exception
			}

			if (isGatherData) {
				DeviceUtils.setAlarm(context,
						ConstantGloble.ALARM_ACTION_GATHER_DATA,
						ConstantGloble.ALARM_REQUEST_GATHER_DATA, gatherPeriod);
			}
			// Add by dhy .. {
			context.startService(new Intent(context, AlertService.class));
			context.startService(new Intent(context, PedometerService.class));
			// } ..end .
			
			
			Intent it = new Intent(context, DaemonService.class);
			it.putExtra(ConstantGloble.EXTRATYPE,
					ConstantGloble.ALARM_ACTION_BOOTLOADTATA_DATA);
			context.startService(it);
			
			
			//LoadUserInfo.getUserInfo(context, false);
			SharedPreferencesUtils.setParam(
					context, "on_off", "1");
			sendOnOff(context);
		} else if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
			SharedPreferencesUtils.setParam(
					context, "on_off", "0");
			sendOnOff(context);
		}
	}

	/**
	 * 上报 开关机状态。
	 * @param context
	 */
	private void sendOnOff(Context context) {
		HashMap<String, Object> copyFrom = new HashMap<String, Object>();
		copyFrom.put(ConstantGloble.REQHEAD,
				DeviceUtils.getreqHeadContent(ConstantGloble.W003, context));
		copyFrom.put(ConstantGloble.BODY, new UploadData(context, 5, 0));
		JSONObject jsonObject = new JSONObject(copyFrom);
		ControlCenter.getInstanse().requestHttp(ConstantGloble.BASE_URL,
				"post", jsonObject, null, null, null, context);
	}
}
